import Service.Utils.StringTransferUtil;
import Service.YibaiChandaoTaskServiceImpl;
import com.mysql.jdbc.StringUtils;
import org.jawin.COMException;
import org.jawin.DispatchPtr;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Main {
    public static void getBack(boolean status) {
        if(status){
            System.out.println("请输入'Y'关闭窗口");
            Scanner input = new Scanner(System.in);

            if (input.hasNext()) {
                while(true){
                    String code = input.next();
                    if("Y".equals(code.toUpperCase())){
                        System.exit(0);
                    }else{
                        System.out.println("其他功能暂未开放，如需重新生成请关闭当前窗口后,重新执行bat文件");
                    }
                }
            }
        }
    }
    public static String getMouth() {
        System.out.println("请输入要查询的月份(例：2019-02)");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Scanner input = new Scanner(System.in);
        String code = input.next();

        try {
            sdf.parse(code);
        } catch (ParseException e) {
            System.out.println("输入月份格式错误，请重新输入...");
            Main.getMouth();
        }
        return  code;
    }
    public static  int getWeek(){
        System.out.println("请输入要查询的周数(仅输入数字 0:本月，1:第一周，2:第二周，3:第三周，4:第四周，5:第五周)");
        Scanner inputWeek = new Scanner(System.in);
        String week = inputWeek.next();
        int weekNum = 0 ;
        try {
            weekNum = Integer.valueOf(week);
        }catch (Exception e){
            System.out.println("请输入正确的周数！");
            Main.getWeek();
        }
        return weekNum;
    }


    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        YibaiChandaoTaskServiceImpl getData = new YibaiChandaoTaskServiceImpl();
        String mouth = Main.getMouth();
        int week = Main.getWeek();
//        List<Map<String, Object>> resultlist =  getData.getAll("2019-02",2);
        List<Map<String, Object>> resultlist =  getData.getAll(mouth,week);
        Map<String,Object> map =  changeDataStructure(resultlist);
        if(map == null){
            System.out.println("你所选择的日期内无数据！请重新输入...");
            Main.main(args);
        }
        DispatchPtr  app = new DispatchPtr();
        try {
            //实例一个app,这个app可以想象成是一个ms project的应用程序
            //这里要指明的一点的是,使用这种方法生成*.mpp文件的前提是你的电脑上必须安装有msproject这个软件
            // 从这个链接中可以发现app有个成员是http://msdn.microsoft.com/en-us/library/bb236984(v=office.12).aspx
            System.out.println("============ project文件开始生成 ============");
            System.out.println("根据数据量来决定，大约需要5-10分，请稍后......");
            app = new DispatchPtr("MSProject.Application");
            // 从这个链接中可以发现app有个成员是http://msdn.microsoft.com/en-us/library/bb236984(v=office.12).aspx
            DispatchPtr projects = (DispatchPtr) app.get("Projects");
            //从这个链接中可以发现http://msdn.microsoft.com/en-us/library/bb214615(v=office.12).aspx
            DispatchPtr project = (DispatchPtr) projects.invoke("Add");
            //生成一个task集合
            DispatchPtr tasks = (DispatchPtr) project.get("Tasks");
            List<Map<String,Object>> hasDemand = (List<Map<String, Object>>) map.get("hasDemand");
            List<Map<String,Object>> noDemand = (List<Map<String, Object>>) map.get("noDemand");
            // 有需求
            if (hasDemand != null && hasDemand.size()>0){
                DispatchPtr task0 = (DispatchPtr) tasks.invoke("Add");
                task0.put("Name", "有需求任务");
                for(Map<String,Object> appNameTemp :hasDemand){
                    DispatchPtr task1 = (DispatchPtr) tasks.invoke("Add");
                    task1.put("Name", appNameTemp.get("appName").toString().trim());
                    task1.put("OutlineLevel", 1);
                    List<Map<String,Object>> demandList = (List<Map<String, Object>>) appNameTemp.get("demandList");
                    for (Map<String,Object> demand :demandList) {
                        DispatchPtr task11 = (DispatchPtr) tasks.invoke("Add");
                        String projectName = demand.get("projectName").toString().trim();
                        task11.put("Name",  StringTransferUtil.replaceBlank(projectName) );
                        task11.put("OutlineLevel", 2);
                        int storyId = (Integer) demand.get("storyNum");
                        task11.put("Text1", storyId);
                        System.out.println("需求id="+storyId);
                        String temp =demand.get("demandCreatePerson").toString().trim();
                        task11.put("Text2", (String)demand.get("demandCreatePerson"));

                        task11.put("Text3", (String)demand.get("demandCreateDate"));
                        task11.put("Text4", (String)demand.get("demandReviewPerson").toString().trim());
                        task11.put("Text5", (String)demand.get("demandReviewDate"));
                        List<Map<String,Object>> taskList = (List<Map<String, Object>>) demand.get("task");
                        for (Map<String,Object> taskMap : taskList) {
                            DispatchPtr task111 = (DispatchPtr) tasks.invoke("Add");
                            task111.put("OutlineLevel", 3);

                            task111.put("Text1", taskMap.get("taskId"));
                            String taskName = ((String) taskMap.get("taskName")).trim();
//                            System.out.println(((String) taskMap.get("taskName")).trim());
                            task111.put("Name", StringTransferUtil.replaceBlank(taskName));
                            Date startDate = (Date) taskMap.get("realStartTime");
                            String startTime = "";
                            Date temp1 = sdf.parse("2018-01-01");
                            Date finishDate = (Date) taskMap.get("realFinishedDate");
                            if(startDate != null){
                                if(startDate.before(temp1)){
                                    if(finishDate != null){
                                        startDate =finishDate;
                                    }else{
                                        startDate = new Date();
                                    }
                                }
                                startTime = sdf.format(startDate);
                            }
                            String finishTime = "";
                            if(finishDate != null){
                                finishTime = sdf.format(finishDate);
                            }


                            task111.put("Start", startTime);
                            task111.put("Finish",finishTime);
                            Double d = (Double)taskMap.get("percentage");
                            d = ( d != null ) ? d : 0D;
                            double value = Double.valueOf(d.toString());
                            task111.put("PercentComplete", d);
                            task111.put("Notes", "test name1" );
                            task111.put("ResourceNames", Main.isNotNullStr(taskMap, "assignedBy") );

                            task111.put("Text6", Main.isNotNullStr(taskMap, "taskStatus") );
                            task111.put("Text7",taskMap.get("sweepMonth") );
                            task111.put("Text8",taskMap.get("weeks") );
                            // 消耗工期
                            int workDays = (Integer) taskMap.get("duration");
                            if(workDays == 0){
                                Date finishDete = (Date) taskMap.get("finishDete");
                                if(finishDate != null){
                                    workDays = 1;
                                }
                            }
                            task111.put("Text9",workDays+"个工作日");
                            //  预计工时
                            Float consumedTime = (Float) taskMap.get("consumedTime");
                            task111.put("Text10",consumedTime);
                        }
                    }
                }
            }else{
                System.out.println("本周"+mouth+"第"+week+"周无有需求任务！");
                Thread.sleep(3000);
            }
            // 无需求
            if (noDemand != null && noDemand.size() > 0){
                DispatchPtr task0 = (DispatchPtr) tasks.invoke("Add");
                task0.put("Name", "自建任务");
                for(Map<String,Object> appNameTemp : noDemand){
                    DispatchPtr task1 = (DispatchPtr) tasks.invoke("Add");
                    String appName = (String) appNameTemp.get("appName").toString().trim();
//                    System.out.println(appName);
//                    System.out.println("============");
                    task1.put("Name", StringTransferUtil.replaceBlank(appName));
                    task1.put("OutlineLevel", 1);
                    List<Map<String,Object>> taskList = (List<Map<String, Object>>) appNameTemp.get("task");
                        for (Map<String,Object> taskMap : taskList) {
                            DispatchPtr task12 = (DispatchPtr) tasks.invoke("Add");
                            task12.put("OutlineLevel", 2);
                            int taskId = (Integer) taskMap.get("taskId");
                            task12.put("Text1", taskId);
                            System.out.println("任务id="+taskId);
                            String taskName = taskMap.get("taskName").toString().trim();
                            task12.put("Name", StringTransferUtil.replaceBlank(taskName));
                            Date startDate = (Date) taskMap.get("realStartTime");
                            Date finishDate = (Date) taskMap.get("realFinishedDate");
                            Date temp = sdf.parse("2019-01-01");

                            String startTime = "";
                            if(startDate != null){
                                if(startDate.before(temp)){
                                    if(finishDate != null){
                                        startDate =finishDate;
                                    }else{
                                        startDate = new Date();
                                    }
                                }
                                startTime = sdf.format(startDate);

                            }
                            String finishTime = "";
                            if(finishDate != null){
                                finishTime = sdf.format(finishDate);
                            }
    //                        String finishTime = (sdf.format(finishDate)!= null)?sdf.format(finishDate):"";
                            task12.put("Start", startTime);
                            task12.put("Finish",finishTime);
                            Double d = (Double) taskMap.get("percentage");
                            d = ( d != null ) ? d : 0D;
                            double value = Double.valueOf(d.toString());
                            task12.put("PercentComplete", d);
                            task12.put("Notes", "test name1" );
                            task12.put("ResourceNames", Main.isNotNullStr(taskMap, "assignedBy") );

                            task12.put("Text6", Main.isNotNullStr(taskMap, "taskStatus") );
                            task12.put("Text7",taskMap.get("sweepMonth") );
                            task12.put("Text8",taskMap.get("weeks") );
                            // 预计工期

                            int workDays = (Integer) taskMap.get("duration");
                            if(workDays == 0){
                                Date finishDete = (Date) taskMap.get("finishDete");
                                if(finishDate != null){
                                    workDays = 1;
                                }
                            }
                            task12.put("Text9",workDays+"个工作日");
                            //  预计工时
                            Float consumedTime = (Float) taskMap.get("consumedTime");
                            task12.put("Text10",consumedTime);

                    }
                }
            }else {
                System.out.println("本周"+mouth+"第"+week+"周无自建任务数据！");
                Thread.sleep(3000);
            }
            String dir = "E:\\tempMSProjectFile\\";
            File projectAddress = new File(dir);
            if(!projectAddress.exists()){
                projectAddress.mkdirs();
            }
            SimpleDateFormat sdfFile = new SimpleDateFormat("yyyy_MM_dd__HH_mm_ss");
            String dateStr = sdfFile.format(Calendar.getInstance().getTime());
            String fileName = "MsProject"+dateStr;
            String fileStr = String.format("%s%s%s",dir,fileName,".mpp");
            project.invoke("SaveAs",fileStr);
            System.out.println("生成project文件成功，文件名为:"+fileStr);
            app.invoke("DocClose" );
            getBack(true);
            System.out.println("============ project文件生成结束 ============");
        } catch (COMException e) {
            e.printStackTrace();
            System.out.println("生成失败请重试！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            try {
                app.invoke("DocClose" );
            } catch (COMException e) {
                e.printStackTrace();
            }
        }

    }
    /**
     *
     * 功能描述: 组装数据结构
     * @date: 2019/3/15 0015
     */
    private static  Map<String,Object> changeDataStructure(List<Map<String, Object>> resultlist) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String,Object>> noList = new ArrayList();
        List<Map<String,Object>> hasList = new ArrayList();
        List<Map<String,Object>> task1List = new ArrayList();
        List<Map<String,Object>> task2List = new ArrayList();
        List<Map<String,Object>> demandList = new ArrayList();
        Set<String> demandSet = new HashSet();
        Set<String> app1Set = new HashSet();
        Set<String> app2Set = new HashSet();

        Map<String,Object> resultMap = new HashMap<>();
        if(resultlist == null || resultlist.size() <= 0){
            return null;
        }
        for (Map<String, Object> row: resultlist) {
//            System.out.println(JSON.toJSON(row).toString());
            Integer str = (Integer) row.get("storyId");
            if(str==null){
                str = 0;
            }
            if(str>0){
                // 系统名称
                String projectName = (String) row.get("projectName");
                // 需求名称
                String storyNumName = (String) row.get("storyNumName");
                // 任务名称
//                String renwmc = (String) row.get("taskNoName");
                // 任务列表
                app1Set.add(projectName);
                demandSet.add(storyNumName);
                task1List.add(row);
            }else{
                // 系统名称
                String projectName = (String) row.get("projectName");
                // 任务名称
//              String renwmc = (String) row.get("taskNoName");
                app2Set.add(projectName);
                task2List.add(row);
            }
        }
        List<Map<String,Object>> tempTask = new ArrayList();
        for (String demand : demandSet) {
            Map<String,Object> demandName = new HashMap<>();
            List<Map<String,Object>> tempTaskList = new ArrayList<>();
            String appTemp = null;
            String demandCreatePerson = null;
            String demandCreateDate = null;
            String demandReviewPerson = null;
            String demandReviewDate = null;
            Integer zentaoNum = null;
            String demandTempName = null;
            for (Map<String,Object> task:task1List) {
                String demandTemp = (String) task.get("storyNumName");

                if(!StringUtils.isNullOrEmpty(demandTemp) && demand.equals(demandTemp)){
                    String appTest = (String) task.get("projectName");
                    String demandCreatePersonTest = (String) task.get("storyDishedBy");
                    Date demandCreateDateTest = (Date) task.get("storyDishedDate");

                    String demandReviewPersonTest = (String) task.get("storyReviewBy");
                    Date demandReviewDateTest = (Date) task.get("storyReviewDate");
                    String dm = (String) task.get("storyNumName");
                    Integer storyNum = (Integer) task.get("storyId");
                    if(!StringUtils.isNullOrEmpty(appTest)){
                        appTemp = appTest;
                    }
                    if(!StringUtils.isNullOrEmpty(demandCreatePersonTest)){
                        demandCreatePerson = demandCreatePersonTest;
                    }
                    if(demandCreateDateTest != null){


                        demandCreateDate = sdf.format(demandCreateDateTest);;
                    }
                    if(!StringUtils.isNullOrEmpty(demandReviewPersonTest)){
                        demandReviewPerson = demandReviewPersonTest;
                    }
                    if(demandReviewDateTest != null){
                        demandReviewDate = sdf.format(demandReviewDateTest);
                    }
                    demandTempName = (!StringUtils.isNullOrEmpty(dm)) ? dm : demand;
                    if( storyNum != null ){
                        zentaoNum = storyNum;
                    }
                    tempTaskList.add(task);

                }
            }
            demandName.put("task", tempTaskList);
            demandName.put("projectName",demand);
            demandName.put("appName",appTemp);
            demandCreatePerson = (demandCreatePerson != null) ? demandCreatePerson: "";
            demandName.put("demandCreatePerson", demandCreatePerson);
            demandCreateDate = (demandCreateDate != null) ? demandCreateDate: "";
            demandName.put("demandCreateDate", demandCreateDate);
            demandReviewPerson = (demandReviewPerson != null) ? demandReviewPerson: "";
            demandName.put("demandReviewPerson", demandReviewPerson);
            demandReviewDate = (demandReviewDate != null) ? demandReviewDate: "";
            demandName.put("demandReviewDate", demandReviewDate);
            zentaoNum = (zentaoNum != null) ? zentaoNum: 0;
            demandName.put("storyNum", zentaoNum);
            demandList.add(demandName);
        }
        for (String app:app1Set) {
            Map appNameTemp = new HashMap();
            List tempDemandList = new ArrayList();
            for(Map<String,Object> map : demandList){
                String appNametemp = (String) map.get("appName");
                if(app.equals(appNametemp)){
                    tempDemandList.add(map);
                }
            }
            appNameTemp.put("appName", app);
            appNameTemp.put("demandList",tempDemandList);
            hasList.add(appNameTemp);
        }

        // 自建任务列表
        for (String app : app2Set) {
//            System.out.println(app);
//            System.out.println("=============");
            Map<String,Object> appTempMap = new HashMap<>();
            List<Map<String,Object>> tempTaskList = new ArrayList<>();
            String appTemp = null;
            String appName = null;
            for (Map<String,Object> task:task2List) {
                appTemp = (String) task.get("projectName");
                if(!StringUtils.isNullOrEmpty(appTemp) && app.equals(appTemp)){
                    appName = app;
                    tempTaskList.add(task);
                }
            }
            appTempMap.put("task", tempTaskList);

            appTempMap.put("appName",appName);
            noList.add(appTempMap);
        }

        resultMap.put("hasDemand", hasList);
        resultMap.put("noDemand", noList);
        return resultMap;
    }
    private static String isNotNullStr (Map<String,Object> taskMap,String str){
        String str1 = (String) taskMap.get(str);
        str1 = (str1 != null) ? str1 : "";
        return str1;
    }
}
